<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>发布招聘会</span>
        <el-button
          style="float: right; padding: 0;margin-left:14px"
          type="text"
          @click="goto('/jobfair/list')"
        >
          返回
        </el-button>
        <el-button
          style="float: right; padding: 0;"
          type="text"
          :disabled="issubmit"
          @click="onSubmit('form')"
        >
          保存
        </el-button>
      </div>
      <el-form
        ref="form"
        class="common-form"
        :model="form"
        label-width="120px"
        :rules="rules"
        :inline-message="true"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" />
          <span class="smalltip">
            <i class="el-icon-info" />
            (如：2017年5月1日医药行业主题招聘会)
          </span>
        </el-form-item>
        <el-form-item label="报名时间" prop="predetermined">
          <el-date-picker
            v-model="form.predetermined"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="举办日期" prop="holddate">
          <el-date-picker
            v-model="form.holddate"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="主办方" prop="sponsor">
          <el-input v-model="form.sponsor" />
        </el-form-item>
        <el-form-item label="联系人" prop="contact">
          <el-input v-model="form.contact" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" />
          <span class="smalltip">
            <i class="el-icon-info" />
            (多个号码请用英文半角逗号“,”隔开)
          </span>
        </el-form-item>
        <el-form-item label="缩略图">
          <el-upload
            class="thumb-uploader"
            :action="apiUpload"
            :headers="headers"
            :show-file-list="false"
            :on-success="handleThumbSuccess"
            :before-upload="beforeThumbUpload"
          >
            <img v-if="form.thumb" :src="thumbUrl" class="thumb">
            <i v-else class="el-icon-plus thumb-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item label="举办地址" prop="address">
          <el-input v-model="form.address" />
        </el-form-item>
        <el-form-item label="乘车路线">
          <el-input v-model="form.bus" />
        </el-form-item>
        <el-form-item v-if="config.is_open_map == 1" label="地图标注">
          <baidu-map
            v-if="config.map_type == 1"
            :ak="config.map_ak"
            class="map"
            :scroll-wheel-zoom="true"
            :center="center"
            :zoom="zoom"
            @click="mapClick"
            @zoomend="syncCenterAndZoom"
          >
            <baidu-map-navigation />
            <bm-marker
              :position="point"
              :dragging="true"
              :z-index="999999999"
              @dragend="mapDragend"
            />
          </baidu-map>
          <TianMap
            v-if="config.map_type == 2"
            class="map"
            :ak="config.tian_map_ak"
            :center="center"
            :zoom="zoom"
            @click="handleTianMapClick"
            @zoomend="handleTianSyncCenterAndZoom"
          >
            <TianMapNavigation />
            <TianMapMarker :position="point" :draggable="true" @dragend="handleTianMapDragend" />
          </TianMap>
        </el-form-item>
        <el-form-item label="招聘会简介" required prop="introduction">
          <div style="border: 1px solid #ccc;">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editor"
              :default-config="toolbarConfig"
            />
            <Editor
              v-model="form.introduction"
              style="height: 400px; overflow-y: hidden;"
              @onCreated="onCreated"
            />
          </div>
        </el-form-item>
        <el-form-item label="附件" prop="attach">
          <el-upload
            class="upload-demo"
            :action="apiAttachUpload"
            :headers="headers"
            :on-remove="handleRemove"
            :file-list="form.attach"
            :on-success="handleAttachSuccess"
            :before-upload="beforeAttachUpload"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传excel,word,ppt,pdf,zip,rar文件，且不超过{{ fileupload_size }}kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="简介配图">
          <el-upload
            class="thumb-uploader"
            :action="apiUpload"
            :headers="headers"
            :show-file-list="false"
            :on-success="handleIntroImgSuccess"
            :before-upload="beforeThumbUpload"
          >
            <img v-if="form.intro_img" :src="introImgUrl" class="thumb">
            <i v-else class="el-icon-plus thumb-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item label="选择展位模板" prop="tpl_id">
          <el-select v-model="form.tpl_id" placeholder="选择模板">
            <el-option
              v-for="(item, index) in positionTpl"
              :key="index"
              :label="item.title"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="ordid">
          <el-input v-model.number="form.ordid" />
          <span class="smalltip">
            <i class="el-icon-info" />
            (数字越大越靠前)
          </span>
        </el-form-item>
        <el-form-item label="参会对象" prop="participants_object">
          <el-input v-model="form.participants_object" type="textarea" rows="4" />
        </el-form-item>
        <el-form-item label="摊位设置及费用" prop="price">
          <el-input v-model="form.price" type="textarea" rows="4" />
        </el-form-item>
        <el-form-item label="参会报名办法" prop="registration_method">
          <el-input v-model="form.registration_method" type="textarea" rows="4" />
        </el-form-item>
        <el-form-item label="">
          <el-button type="primary" :disabled="issubmit" @click="onSubmit('form')">保存</el-button>
          <el-button @click="goto('/jobfair/list')">返回</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { jobfairAdd, jobfairPositionTpl } from '@/api/jobfair'
import BaiduMap from 'vue-baidu-map/components/map/Map.vue'
import BaiduMapNavigation from 'vue-baidu-map/components/controls/Navigation.vue'
import BmMarker from 'vue-baidu-map/components/overlays/Marker' // 点标注
import TianMap from '@/components/map/TianMap/TianMap.vue'
import TianMapNavigation from '@/components/map/TianMap/Navigation.vue'
import TianMapMarker from '@/components/map/TianMap/Marker.vue'
import apiArr from '@/api'
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

export default {
  components: {
    BaiduMap,
    BmMarker,
    BaiduMapNavigation,
    Editor,
    Toolbar,
    TianMap,
    TianMapNavigation,
    TianMapMarker
  },
  data() {
    var validateIntroduction = (rule, value, callback) => {
      value = this.editor.getText()
      if (value === '') {
        callback(new Error('请输入招聘会简介'))
      } else {
        callback()
      }
    }
    return {
      editor: null,
      toolbarConfig: {
        excludeKeys: [
          'fullScreen'
        ]
      },
      headers: { admintoken: getToken() },
      fileupload_size: '',
      fileupload_ext: '',
      apiUpload: window.global.RequestBaseUrl + apiArr.upload,
      apiAttachUpload: window.global.RequestBaseUrl + apiArr.uploadAttach,
      thumbUrl: '',
      introImgUrl: '',
      positionTpl: [],
      center: { lng: '', lat: '' },
      point: { lng: '', lat: '' },
      zoom: 0,
      form: {
        title: '',
        holddate: '',
        predetermined: '',
        sponsor: '',
        contact: '',
        attach: [],
        phone: '',
        thumb: '',
        address: '',
        bus: '',
        map_lat: '',
        map_lng: '',
        map_zoom: '',
        introduction: '',
        intro_img: '',
        tpl_id: '',
        ordid: 0,
        participants_object: '',
        price: '',
        registration_method: ''
      },
      issubmit: false,
      rules: {
        title: [
          { required: true, message: '请填写招聘会标题', trigger: 'blur' },
          { max: 200, message: '长度在 1 到 200 个字符', trigger: 'blur' }
        ],
        holddate: [
          { required: true, message: '请选择招聘会举办时间', trigger: 'blur' }
        ],
        predetermined: [
          { required: true, message: '请选择招聘会报名时间', trigger: 'blur' }
        ],
        sponsor: [
          { required: true, message: '请填写招聘会主办方', trigger: 'blur' },
          { max: 200, message: '长度在 1 到 200 个字符', trigger: 'blur' }
        ],
        contact: [
          { required: true, message: '请填写联系人', trigger: 'blur' },
          { max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请填写联系电话', trigger: 'blur' },
          { max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请填写举办地址', trigger: 'blur' },
          { max: 200, message: '长度在 1 到 200 个字符', trigger: 'blur' }
        ],
        introduction: [{ validator: validateIntroduction, trigger: 'blur' }],
        tpl_id: [
          { type: 'number', message: '请正确选择模板', trigger: 'blur' }
        ],
        ordid: [
          { type: 'number', message: '排序必须为数字', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    config() {
      return this.$store.state.config
    }
  },
  mounted() {

  },
  created() {
    this.center = { lng: this.$store.state.config.map_lng, lat: this.$store.state.config.map_lat }
    this.point = this.center
    this.zoom = parseInt(this.$store.state.config.map_zoom)
    this.form.map_lng = this.point.lng
    this.form.map_lat = this.point.lat
    this.form.map_zoom = this.zoom
    this.fileupload_size = this.config.fileupload_size
    this.fileupload_ext = this.config.fileupload_ext
    this.getPositionTpl()
  },
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
  },
  methods: {
    // 天地图点击
    handleTianMapClick(e){
      this.point = e.lnglat
      this.form.map_lat = e.lnglat.lat
      this.form.map_lng = e.lnglat.lng
    },
    // 天地图缩放结束
    handleTianSyncCenterAndZoom(e){
      this.form.map_zoom = e.target.getZoom()
    },
    // 天地图标记的拖拽结束
    handleTianMapDragend(e){
      this.form.map_lat = e.lnglat.lat
      this.form.map_lng = e.lnglat.lng
    },
    onCreated(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
      this.editor.getMenuConfig('uploadImage').headers = {
        admintoken: getToken()
      }
      this.editor.getMenuConfig('uploadImage').withCredentials = true
      this.editor.getMenuConfig('uploadImage').server = window.global.RequestBaseUrl + apiArr.uploadEditor
      this.editor.getMenuConfig('uploadVideo').headers = {
        admintoken: getToken()
      }
      this.editor.getMenuConfig('uploadVideo').withCredentials = true
      this.editor.getMenuConfig('uploadVideo').server = window.global.RequestBaseUrl + apiArr.uploadEditorVideo
    },
    getPositionTpl: function(){
      var t = this
      jobfairPositionTpl().then(res => {
        t.positionTpl = res.data.items
      })
    },
    mapClick: function(e) {
      this.point = e.point
      this.form.map_lat = e.point.lat
      this.form.map_lng = e.point.lng
    },
    mapDragend: function(e){
      this.form.map_lat = e.point.lat
      this.form.map_lng = e.point.lng
    },
    syncCenterAndZoom: function(e){
      this.form.map_zoom = e.target.getZoom()
    },
    handleThumbSuccess(res, file) {
      if (res.code == 200) {
        this.thumbUrl = URL.createObjectURL(file.raw)
        this.form.thumb = res.data.file_id
      } else {
        this.$message.error(res.message)
        return false
      }
    },
    handleIntroImgSuccess(res, file) {
      if (res.code == 200) {
        this.introImgUrl = URL.createObjectURL(file.raw)
        this.form.intro_img = res.data.file_id
      } else {
        this.$message.error(res.message)
        return false
      }
    },
    beforeThumbUpload(file) {
      const filetypeArr = file.type.split('/')
      const filetype = filetypeArr[1]
      const configFileExtArr = this.fileupload_ext.split(',')

      if (!configFileExtArr.includes(filetype)) {
        this.$message.error('上传文件格式不允许')
        return false
      }
      if (file.size / 1024 > this.fileupload_size) {
        this.$message.error(`上传文件最大为${this.fileupload_size}kb`)
        return false
      }
      return true
    },
    onSubmit(formName) {
      // 重复点击修改 zch 2022/7/25
      this.issubmit = true
      const that = this
      this.form.introduction = this.editor.getHtml()
      var insertData = Object.assign({}, this.form)
      this.$refs[formName].validate(valid => {
        if (valid) {
          insertData['holddate_start'] = new Date(insertData.holddate[0]).getTime() / 1000
          insertData['holddate_end'] = new Date(insertData.holddate[1]).getTime() / 1000
          insertData['predetermined_start'] = new Date(insertData.predetermined[0]).getTime() / 1000
          insertData['predetermined_end'] = new Date(insertData.predetermined[1]).getTime() / 1000
          jobfairAdd(insertData).then(response => {
            this.$message.success(response.message)
            setTimeout(function() {
              that.$router.push('/jobfair/list')
            }, 1500)
            return true
          }).catch(() => {
            that.issubmit = false
          })
        } else {
          that.issubmit = false
          return false
        }
      })
    },
    goto(target) {
      this.$router.push(target)
    },
    handleRemove(file, fileList) {
      const index = this.form.attach.indexOf({ name: file.name, url: file.url })
      this.form.attach.splice(index, 1)
    },
    handleAttachSuccess(res, file) {
      if (res.code == 200) {
        const info = { name: res.data.name, url: res.data.url }
        this.form.attach.push(info)
      } else {
        this.$message.error(res.message)
        return false
      }
    },
    beforeAttachUpload(file) {
      const configFileExtArr = 'doc,docx,xls,xlsx,csv,ppt,pptx,pdf,zip,rar'
      const filename_arr = file.name.split('.')
      const filetype = filename_arr[filename_arr.length - 1]
      if (!configFileExtArr.includes(filetype)) {
        this.$message.error('上传文件格式不允许')
        return false
      }
      if (file.size / 1024 > this.fileupload_size) {
        this.$message.error(`上传文件最大为${this.fileupload_size}kb`)
        return false
      }
      return true
    }
  }
}
</script>
<style scoped>
.map {
  height: 400px;
  max-width: 800px;
  position: relative;
  z-index: 1;
}
.thumb-uploader {
  display: inline-block;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  width: 122px;
  height: 122px;
}
.thumb-uploader img {
  width: 120px;
  height: 120px;
  border-radius: 6px;
}
.thumb-uploader:hover {
  border-color: #409eff;
}
.thumb-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.el-textarea,
.el-select,
.el-input,
.el-date-editor {
  width: 450px;
}
</style>

